package com.ssm.web;


import com.ssm.Entity.User;
import org.springframework.stereotype.Controller;
import com.ssm.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("selectAll")
    @ResponseBody
    public ModelAndView selectUser(@RequestParam int currentPage,
                                   @RequestParam  int pageSize, ModelAndView modelAndView){
        List<User> users = userService.selectAllUser(currentPage,pageSize);
        int total = userService.getTotal();
        modelAndView.addObject("users",users);
        modelAndView.addObject("currentPage",currentPage);
        modelAndView.addObject("pageSize",pageSize);
        modelAndView.addObject("totalPage",total/pageSize+1);
        modelAndView.addObject("total",total);
        modelAndView.setViewName("showUser");
        return modelAndView;
    }

    @RequestMapping("addUser")
    @ResponseBody
    public ModelAndView addUser(User user, ModelAndView modelAndView, HttpSession session1){
        int result = 0;

        result = userService.addUser(user); //调用接口中 定义的数据库操作方法
        if (result != 1) {
            throw new RuntimeException("添加用户失败");
        }
        int userId = userService.userLogin(user);
        session1.setAttribute("loggedIn", userId);
        modelAndView.setViewName("createFolder");
        return modelAndView;
    }

    @RequestMapping("userLogin")
    @ResponseBody
    public ModelAndView userLongin(User user, HttpSession session1) {
        int result = 0;

        result = userService.userLogin(user); //调用接口中 定义的数据库操作方法
        if (result == 0) {
            throw new RuntimeException("用户登录失败");
        }
        session1.setAttribute("loggedIn", result);
        ModelAndView modelAndView = new ModelAndView("redirect:/folder/showFolder");

        return modelAndView;
    }
}
